package com.ladybug.flow.modules.system.service.impl;

import com.ladybug.flow.common.cache.RedisCache;
import com.ladybug.flow.common.security.dto.LoginUserDTO;
import com.ladybug.flow.common.utils.JwtUtil;
import com.ladybug.flow.common.vo.ResponseResult;
import com.ladybug.flow.modules.system.domain.entitys.SysUser;
import com.ladybug.flow.modules.system.service.LoginServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
* @description: TODO
* @author long
* @date 2022/10/14 15:06
* @version 1.0
*/
@Service
public class LoginServiceImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(SysUser user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误!!");
        }
        //使用userid生成token
        LoginUserDTO loginUserDTO = (LoginUserDTO) authenticate.getPrincipal();
        String userId = loginUserDTO.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId, loginUserDTO);
        //redisCache.setCacheObject(jwt+","+userId, loginUserDTO);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("access_token",jwt);
        return new ResponseResult(200,"登陆成功",map);
    }
    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUserDTO loginUserDTO = (LoginUserDTO) authentication.getPrincipal();
        String userid = loginUserDTO.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");
    }
}
